//
// Created by lwj66 on 24-6-10.
//
#include "linkedList.h"

void pushBack(SL** ps, slType value)
{
    assert(ps);
    SL* newList = (SL*)malloc(sizeof (SL));
    if(newList == NULL)
    {
        perror("开辟空间失败!\n");
        exit(1);
    }
    newList->next = NULL;
    newList->ls = value;

    if(*ps == NULL)
    {
        *ps = newList;
        return;
    }

    SL* t = *ps;
    while (t->next)
        t = t->next;
    t->next = newList;
}

void pushFront(SL** ps, slType value)
{
    assert(ps);
    SL* newList = (SL*) malloc(sizeof (SL));
    if(newList == NULL)
    {
        perror("开辟空间失败!\n");
        exit(1);
    }
    newList->next = NULL;
    newList->ls = value;

    newList->next = *ps;
    *ps = newList;
}

void popBack(SL** ps)
{
    assert(ps);
    if(*ps == NULL)
    {
        printf("链表为空, 无法删除!\n");
        return;
    }

    if((*ps)->next == NULL)
    {
        free(*ps);
        *ps = NULL;
        return;
    }

    SL* t = *ps;
    while (t->next->next)
        t = t->next;
    free(t->next);
    t->next = NULL;
}

void popFront(SL** ps)
{
    assert(ps);
    if(*ps == NULL)
    {
        printf("链表为空, 无法删除!\n");
        return;
    }
    SL* temp = *ps;
    *ps = (*ps)->next;
    free(temp);
}

void insertAT(SL** ps, slType value, size_t index)
{
    assert(ps);
    SL* newList = (SL*)malloc(sizeof (SL));
    if(newList == NULL)
    {
        perror("开辟空间失败!\n");
        exit(1);
    }
    newList->next = NULL;
    newList->ls = value;

    if(index == 0)
    {
        newList->next = *ps;
        *ps = newList;
        return;
    }

    if(*ps == NULL)
    {
            printf("输入错误, 请重新输入!\n");
            free(newList);
            return;
    }

    SL* t = *ps;
    while (--index && t->next != NULL)
        t = t->next;
    if(index != 0)
    {
        printf("输入错误, 请重新输入 : ");
        free(newList);
        return;
    }
        newList->next = t->next;
        t->next = newList;
}

void removeAT(SL** ps, size_t index)
{
    assert(ps);
    if(*ps == NULL)
    {
        printf("链表为空, 无法删除!");
        return;
    }

    if(index == 0)
    {
        SL* temp = *ps;
        *ps = (*ps)->next;
        free(temp);
        return;
    }

    SL* t = *ps;
    while (--index && t->next != NULL)
        t = t->next;
    if(index != 0 || t->next == NULL)
    {
        printf("索引输入错误, 请重新输入!\n");
        return;
    }

    SL* n = t->next->next;
    free(t->next);
    t->next = n;
}

void listPrint(SL** ps)
{
    assert(ps);
    SL* t = *ps;
    while (t != NULL)
    {
        printf(TYPESPECIFIER, t->ls);
        t = t->next;
    }
    printf("NULL\n");
}

void listClear(SL** ps)
{
    assert(ps);
    SL* t;
    while (*ps)
    {
        t = (*ps)->next;
        free(*ps);
        *ps = t;
    }
}

int listFind(SL** ps, slType value)
{
    assert(ps);
    if(*ps == NULL) return 0;
    SL* t = *ps;
    do
    {
        if(t->ls == value)
            return 1;
        t = t->next;
    } while (t);
    return 0;
}